package com.mongodb;


import com.mongodb.entity.User;
import com.mongodb.server.IUserServer;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.annotation.Resource;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.UUID;

/**
 * @author Conceit
 * @version 1.0, 2017/1/9
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:/spring-context.xml", "classpath*:/spring-mybatis.xml", "classpath*:/spring-mvc.xml"})
public class TestConection {

    @Resource
    IUserServer userServerImpl;

    @Test
    public void saveUser() {
        for (int i = 0; i < 5; i++) {
            User user = new User();
            user.setBirthday(new Date());
            user.setEmail(new String("test@163.com"));
            user.setSex(new String("man"));
            user.setUserId(UUID.randomUUID().toString());
            user.setUserName("测试姓名" + i);
            userServerImpl.saveUser(user);
        }
    }

    @Test
    public void connectionMongo() {

        // 连接到 mongodb 服务
        Mongo mongo = null;
        try {
            mongo = new Mongo("127.0.0.1", 27017);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        //根据mongodb数据库的名称获取mongodb对象 ,
        DB db = mongo.getDB("user_db");
        //校验用户密码是否正确
        if (!db.authenticate("zhaohang", "zhaohang123".toCharArray())) {
            System.out.println("连接MongoDB数据库,校验失败！");
        } else {
            Set<String> collectionNames = db.getCollectionNames();
            // 打印出test中的集合
            for (String name : collectionNames) {
                System.out.println("collectionName===" + name);
            }

        }
    }


    @Test
    public void findOneByUserId() {
        String userId = "214da1c3-304c-41ad-911d-1badc209d21f";
        User user = userServerImpl.findOneByUserId(userId);
        System.out.println(user.getUserName());
    }

    @Test
    public void findAllUserByName() {
        String name = "测试";
        List<User> userList = userServerImpl.findAllUserByName(name);
        for (User user : userList) {
            System.out.println(user.getUserName());
        }
        System.out.println("查询完毕!查询结果为：" + userList.size());
    }

    @Test
    public void findUsersByTime() {
        Date endTime = new Date();
        Date startTime = new Date(endTime.getTime() - 10 * 60 * 60 * 1000);
        List<User> userList = userServerImpl.findUsersByTime(startTime, endTime);
        System.out.println("查询完毕!查询结果为：" + userList.size());
    }
}
